package com.alipay.disruptor;

import com.alipay.traditionalbus.EventPublisher;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by crazytime on 14-3-2.
 */
public class LongEventMain {
    public static void main(String[] args) throws InterruptedException {
        // Executor that will be used to construct new threads for consumers
        Executor executor = Executors.newFixedThreadPool(3);

        // The factory for the event
        LongEventFactory factory = new LongEventFactory();

        LongEventHandler handler=new LongEventHandler();

        // Specify the size of the ring buffer, must be power of 2.
        int bufferSize = 1024;

        // Construct the Disruptor
        Disruptor<LongEvent> disruptor = new Disruptor(factory, bufferSize, executor);

        disruptor.handleEventsWith(handler);
        // Start the Disruptor, starts all threads running
        disruptor.start();

        // Get the ring buffer from the Disruptor to be used for publishing.
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

        LongEventProducer producer = new LongEventProducer(ringBuffer);

        ByteBuffer bb = ByteBuffer.allocate(8);
        long start=System.nanoTime();
        long ITERATIONS = 1000L * 1000L * 100L;

        int readThreadNum=20;
        CountDownLatch pub=new CountDownLatch(readThreadNum);
        Thread[] group=initPublishThread(20,ITERATIONS,pub,producer);
        for(Thread it:group){
            it.start();
        }
        pub.await();
        long duration=System.nanoTime()-start;
        long ops = (ITERATIONS * 1000L * 1000L * 1000L) / duration;
        System.out.format("ops/sec    = %,d\n", ops);
    }

    public static Thread[] initPublishThread(int num,long allCounts,CountDownLatch pub,LongEventProducer producer){
        Thread[] thread=new Thread[num];
        long step=allCounts/num;
        for(int i=0;i<num;i++){
            thread[i]=new Thread(new LongEventDisruptorPublisher(step,1000,producer,pub));
        }
        return thread;
    }


}
